/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.h2t.loveplace.utils;

import com.sun.lwuit.Image;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

public class Storage {

    private static String folder = "file:///E:/loveplace/";
    private FileConnection fileConnection;

    public static Image loadImg(String fileName) {
        System.out.println("File: " +fileName);
        FileConnection fileConn = null;
        DataInputStream dis = null;
        Image img = null;
        try {
            fileConn = (FileConnection) Connector.open(folder + fileName + ".png");
            dis = fileConn.openDataInputStream();
            img = Image.createImage(dis);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            dis.close();
            fileConn.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        
        return img;
    }

    public static String storeImg(byte[] imgByte) {
        FileConnection fileConn = null;
        String fileName = folder + System.currentTimeMillis() + ".png";
        System.out.println("filename: " + fileName);
        DataOutputStream dos = null;
        try {
            fileConn = (FileConnection) Connector.open(folder);
            if(!fileConn.exists()) {
                fileConn.mkdir();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        try {
            fileConn = (FileConnection) Connector.open(fileName);

            if (!fileConn.exists()) {
                fileConn.create();
                System.out.println("file created");
            }
            dos = new DataOutputStream(fileConn.openOutputStream());
            dos.write(imgByte);
            dos.flush();
            dos.close();
            fileConn.close();
            return fileName;

        } catch (IOException ioe) {
            System.out.println("Error!" + ioe);
        }
        return null;
    }
}
